<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace Admin\Controller;

/**
 * Description of BrandController
 *
 * @author qingf
 */
class PermissionController extends \Think\Controller
{

    /**
     * @var \Admin\Model\PermissionModel
     */
    private $_model = null;

    protected function _initialize()
    {
        $this->_model = D('Permission');
    }

    public function index()
    {
        //获取品牌列表
        $this->assign($this->_model->getList());
        $this->display();
    }

    public function add()
    {
        if (IS_POST) {
            //收集数据
            if ($this->_model->create() === false) {
                $this->error(get_error($this->_model));
            }
            /*var_dump(I('post.'));
            exit;*/
            if ($this->_model->addPermission() === false) {
                $this->error(get_error($this->_model));
            }
            $this->success('添加成功', U('index'));
        } else {
            $this->before_view();

            $this->display();
        }
    }

    public function edit($id)
    {
        if (IS_POST) {
            //收集数据
            if ($this->_model->create() === false) {
                $this->error(get_error($this->_model));
            }

            if ($this->_model->savePermission($id) === false) {
                $this->error(get_error($this->_model));
            }
            $this->success('修改成功', U('index'));
        } else {
            //展示数据
            $row = $this->_model->findPermission($id);
            $this->assign('row', $row);
            //获取所有的分类
            $this->before_view();
            $this->display('add');
        }
    }

    public function remove($id)
    {
        if ($this->_model->deletePermission($id) === false) {
            $this->error(get_error($this->_model));
        } else {
            $this->success('删除成功', U('index'));
        }
    }

    public function removeGallery($id)
    {
        if (M('GoodsGallery')->delete($id) === false) {
            $this->error('删除失败');
        } else {
            $this->success('删除成功');
        }
    }

    private function before_view()
    {
        $permissions = $this->_model->getPermissions();
        array_unshift($permissions, ['id' => 0, 'name' => '顶级分类', 'parent_id' => 0]);
        $permissions = json_encode($permissions);
        $this->assign('permissions',$permissions);
    }

}
